package com.snow.useviewdemo.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityManagerCompat;

import com.snow.useviewdemo.function.phonesystem.PhoneAppInfoBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

/**
 * Created by zhaoyingtao
 * Date: 2020/7/18
 * Describe:
 */
public class PhoneAppUtils {
    private volatile static PhoneAppUtils appUtils;

    public static PhoneAppUtils init() {
        if (appUtils == null) {
            synchronized (PhoneAppUtils.class) {
                if (appUtils == null) {
                    appUtils = new PhoneAppUtils();
                }
            }
        }
        return appUtils;
    }

    /**
     * 获取安装应用的信息
     *
     * @param packageManager
     * @return
     */
    public List<PhoneAppInfoBean> scanLocalInstallAppList(PackageManager packageManager) {
        List<PhoneAppInfoBean> myAppInfos = new ArrayList<PhoneAppInfoBean>();
        if (packageManager == null) {
            return myAppInfos;
        }
        try {
            List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
            for (int i = 0; i < packageInfos.size(); i++) {
                PackageInfo packageInfo = packageInfos.get(i);

                long firstInstallTime = packageInfo.firstInstallTime;// 应用第一次安装的时间
                int versionCode = packageInfo.versionCode;// 应用现在的版本号
                String versionName = packageInfo.versionName;// 应用现在的版本名称
                long lastUpdateTime = packageInfo.lastUpdateTime;// 最后一次更新时间

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Log.e("Steven", "firstInstallTime=" + format.format(firstInstallTime) +
                        ",versionCode=" + versionCode + ",versionName=" + versionName +
                        ",最后更新时间 = " + format.format(lastUpdateTime));

                //如下可获得更多信息
                ApplicationInfo applicationInfo = packageInfo.applicationInfo;
                String name = applicationInfo.name;// Application类名
                String packageName = applicationInfo.packageName;// 包名

                String applicationName =
                        (String) packageManager.getApplicationLabel(applicationInfo);

                Log.e("Steven", "ApkTool.scanLocalInstallAppList：" + "应用名：" + applicationName + ",包名:" + packageName);

                //过滤掉系统app
//                if ((ApplicationInfo.FLAG_SYSTEM & packageInfo.applicationInfo.flags) != 0) {
//                    continue;
//                }
                PhoneAppInfoBean myAppInfo = new PhoneAppInfoBean();
                myAppInfo.setAppName(applicationName);
                myAppInfo.setAppPackage(packageName);
                if (packageInfo.applicationInfo.loadIcon(packageManager) == null) {
                    continue;
                }
                myAppInfo.setAppIcon(packageInfo.applicationInfo.loadIcon(packageManager));
                myAppInfos.add(myAppInfo);
            }
        } catch (Exception e) {
            Log.e("Steven", "===============获取应用包信息失败");
        }
        return myAppInfos;
    }

    /**
     * app是否被安装
     *
     * @param appPackageName
     * @return
     */
    public static boolean isAppInstall(Context context, String appPackageName) {
        PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (appPackageName.equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 通过包名直接打开APP
     *
     * @param context
     * @param packageName
     */
    public static void openInstallApp(Context context, String packageName) {
        if (!TextUtils.isEmpty(packageName)) {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
//            intent.setComponent(new ComponentName(packageName));
            context.startActivity(intent);
        }
    }

    /**
     * 通过协议打开其他app，并跳转指定页面
     *
     * @param context
     * @param packageName
     * @param agreementUrl openapp.jdmobile://virtual?params={"category":"jump","des":"m","url":"https://u.jd.com/txN8JTo","keplerID":"0","keplerFrom":"1","kepler_param":{"source":"kepler-open","otherData":{"mopenbp7":"0"}},"union_open":"union_cps"}
     */
    public static void openInstallAppFromUrl(Context context, String packageName, String agreementUrl) {
        if (context == null || context.getApplicationContext() == null) {
            return;
        }
        if (TextUtils.isEmpty(agreementUrl)) {
            openInstallApp(context, packageName);
            return;
        }
        Intent intent = new Intent();
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.intent.action.VIEW");
        Uri uri = Uri.parse(agreementUrl);
        intent.setData(uri);
        context.getApplicationContext().startActivity(intent);
    }

    /**
     * 是否是内存不足的low的手机设备
     * @param context
     * @return
     */
    public static boolean isLowRamDevice(Context context) {
        boolean isLowRamDevice = false;
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager != null) {
            isLowRamDevice = ActivityManagerCompat.isLowRamDevice(activityManager);
        }
        return isLowRamDevice;
    }
}
